

import React, { useState, useEffect } from 'react'
import { Form, Input, Button, Checkbox, Row, Col } from 'antd';
import { UserOutlined, LockOutlined, MessageOutlined, ShakeOutlined } from '@ant-design/icons';
import { Link, withRouter } from 'react-router-dom';
import { reg } from '../../utils/validate';
import { toast } from '../../utils/common';
import { ajax } from '../../api';
const layout = {
    labelCol: {
        span: 4,
        offset: 1
    },
    wrapperCol: {
        span: 18,
        offset: 1
    }
}



function LoginPhone(props: any) {
    const { location, history } = props
    const [form] = Form.useForm()
    const [toggle, setToggle] = useState<boolean>(false);
    const [flag, setFlag] = useState<boolean>(true);
    let [count, setCount] = useState<number>(120)
    let timer: any = null
    const onFinish = async (value: any) => {
        console.log(value);

        let { code, result, token }: any = await ajax.verifycaptcha(value)
        if (code == 200) {
            localStorage.setItem("phone", value.phone)
            sessionStorage.setItem("autoken", token)
            history.push("/main")
        }
    }
    const onFinishFailed = () => {
        toast.error("请完善数据再提交")
    }

    useEffect(() => {
        var phone = new URLSearchParams(location.search).get("phone")
        if (phone) {
            form.setFieldsValue({ "phone": phone })
            setToggle(false)
        } else {
            var phone = localStorage.getItem("phone")
            if (phone) {
                form.setFieldsValue({ "phone": phone })
                setToggle(false);
            }
        }
    }, [])

    const chechPhone = () => {


        form.validateFields(["phone"])
            .then(res => {
                setToggle(false)
            })
            .catch(err => {
                setToggle(true)
            })
    }


    const countDown = () => {
        setCount(--count)
        setFlag(false)
        timer = setInterval(() => {
            if (count > 0) {
                setCount(--count)
                setFlag(false)
            } else {
                setCount(120);
                setFlag(true)
                clearInterval(timer)
                timer = null
            }
        }, 1000)
    }
    const sendCaptcha = async () => {
        countDown()
        let { code, result }: any = await ajax.sendcaptcha({
            phone: form.getFieldValue("phone")
        })


    }

    return (
        <div>
            <Form
                name="norma_login"
                className='login-form'
                initialValues={{
                }
                }
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                {...layout}
                // ref={uForm}
                form={form}
                autoComplete="off"
            >
                <Form.Item
                    label="手机号:"
                    name="phone"
                    rules={[{ required: true, message: '手机号!' }, { pattern: reg.phone, message: "请输入正确手机号" }]}
                >
                    <Input onChange={chechPhone} prefix={<ShakeOutlined className="site-from-item-icon" />} placeholder='请输入手机号' />
                </Form.Item>

                <Form.Item
                    label="验证码:"
                    name="captcha"
                    rules={[{ required: true, message: '请输入验证码!' }, {
                        pattern: reg.code, message: "请输入4位验证码"
                    }]}
                >
                    <Row>
                        <Col span={14}>
                            <Input prefix={<MessageOutlined className="site-form-item-icon" />} placeholder="请输入验证号码" />
                        </Col>
                        <Col span={9} offset={1}>
                            {
                                flag ? <Button type="primary" onClick={sendCaptcha} disabled={toggle} > 发送验证码</Button>
                                    :
                                    <Button disabled > {'剩余 ' + count + " S"}</Button>
                            }
                        </Col>
                    </Row>

                </Form.Item>



                <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
                    <Button type="primary" htmlType="submit" block >
                        登录
                    </Button>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
                    <div className='links' style={{ width: "100%", display: "flex", justifyContent: "space-between" }}>
                        <Link style={{ color: "#f50" }} to="/register" >没有帐号，立即注册</Link>
                        <Link to="/forgetpass">忘记密码？</Link>

                    </div>
                </Form.Item>

            </Form>
        </div>
    )
}



export default withRouter(LoginPhone)